package com.du.web.sample.util.water;


import com.du.web.sample.util.ContentEnum;
import com.du.web.sample.util.FileTypeUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @desc:
 * @author: shuangdu
 * @date: 2021/9/14
 * @since: 1.8
 */
@Slf4j
public class WaterMakeUtil {

    /**
     * 添加水印
     * <p>
     *     目前支持图片、pdf和docx
     *     初步开发阶段，未做大量测试
     *     todo 需要添加其他类型 doc等
     * </p>
     * @param waterMakeParam
     */
    public static void make(WaterMakeParam waterMakeParam) {
        repeatInputStream(waterMakeParam);
        ContentEnum type = FileTypeUtil.getType(waterMakeParam.getTypeInputStream(), waterMakeParam.getFileName());
        // begin
        WaterMaker waterMaker;
        switch (type) {
            case PIC:
                waterMaker = new PicWaterMaker(waterMakeParam);
                waterMaker.doMake();
                break;
            case PDF:
                waterMaker = new PdfWaterMaker(waterMakeParam);
                waterMaker.doMake();
                break;
            case WORD:
                waterMaker = new WordWaterMaker(waterMakeParam);
                waterMaker.doMake();
                break;
            case OTHER:
                log.warn("该类型暂不支持.");
        }
    }

    /**
     * 将输入流复制多份
     * @param waterMakeParam
     * @return
     */
    private static void repeatInputStream(WaterMakeParam waterMakeParam) {
        // 将InputStream对象转换成ByteArrayOutputStream
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        try {
            while ((len = waterMakeParam.getFileInputStream().read(buffer)) > -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            // 将byteArrayOutputStream可转换成多个InputStream对象，达到多次读取InputStream效果
            waterMakeParam.setTypeInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
            waterMakeParam.setWaterInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
